package com.example.module_mine.login

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.constans.IntentData
import com.example.lib_common.getAttrValue
import com.example.lib_common.utils.ToastUtils
import com.example.lib_common.utils.ValidUtil
import com.example.module_mine.R
import com.example.module_mine.databinding.FragmentPhoneLoginBinding
import com.example.module_mine.login.helper.PopupAgreementHelper
import com.example.module_mine.login.viewmodel.LoginViewModel

/**
 * 手机号登陆页面
 */
class PhoneLoginFragment : BaseFragment<LoginViewModel,FragmentPhoneLoginBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_phone_login
    override val mViewModel: LoginViewModel by activityViewModels() //注意：几个fragment公用同一个viewmodel
    //导航控制器
    private lateinit var mNavController: NavController
    //是否勾选
    private var mLoginAgreement: Boolean = false
    //弹出窗体
    private val mPopupAgreement by lazy {
        PopupAgreementHelper(layoutInflater)
    }


    override fun initView() {
        //设置当前正在显示的fragment
        mViewModel.setCurrentFragment(PhoneLoginFragment::class.simpleName.toString())
        //导航控制器
        mNavController = Navigation.findNavController(mBinding.root)
        //初始化底部view
        initAgreementView()
        //初始化复选框
        initAgreementCheckBox(mLoginAgreement)
    }

    override fun initData() {
        mBinding.viewModel = mViewModel
    }

    override fun initListener() {
        //复选框点击
        mBinding.vChecked.setOnClickListener {
            mLoginAgreement = !mLoginAgreement
            initAgreementCheckBox(mLoginAgreement)
        }
        //获取验证码点击
        mBinding.btnSmsCode.setOnClickListener {
            checkPhone()
        }
        //键盘上完成键点击
        mBinding.etPhone.setOnEditorActionListener { v, actionId, event ->
            if(actionId === EditorInfo.IME_ACTION_DONE){
                checkPhone()
            }
            true
        }
    }

    /**
     * 校验手机号
     */
    private fun checkPhone() {
        val phone = mViewModel.phone.value
        //手机号格式不对
        if(!ValidUtil.phoneNumberValid(phone)){
            ToastUtils.showShort(requireContext(),"手机号格式不正确")
            return
        }
        //未勾选
        if(!mLoginAgreement){
            hideSoftKeyBroad(mBinding.etPhone)
            mPopupAgreement.show(mBinding.btnCheck)
            return
        }
        //跳转到验证码页面
        val bundle = Bundle().apply {
            putString(IntentData.KEY_ACTION_SMS_CODE,SmsCode.LOGIN.type) //登陆验证码
        }
        mNavController.navigate(R.id.action_phoneLoginFragment_to_smsCodeFragment,bundle)

    }

    /**
     * 初始化复选框状态
     */
    private fun initAgreementCheckBox(checked:Boolean){
        if(checked){
            mBinding.btnCheck.background = ContextCompat.getDrawable(requireContext(),R.mipmap.icon_checked)
        }else{
            mBinding.btnCheck.background = ContextCompat.getDrawable(requireContext(),R.mipmap.icon_uncheck)
        }

    }

    /**
     * 初始化用户协议、隐私政策-富文本
     */
    private fun initAgreementView(){
        val colorMain = getAttrValue(requireContext(), com.example.lib_common.R.attr.colorTheme)
        val userAgreement = "《用户协议》"
        val privacyPolicy = "《隐私政策》"
        val content = "阅读并同意$userAgreement 和$privacyPolicy"
        val spannableStringBuilder = SpannableStringBuilder(content)
        val userAgreementStart = content.indexOf(userAgreement) //开始
        val userAgreementEnd = userAgreementStart + userAgreement.length //结束
        val privacyPolicyStart = content.indexOf(privacyPolicy)//开始
        val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length//结束
        //用户协议
        spannableStringBuilder.setSpan(object :ClickableSpan(){
            override fun onClick(widget: View) {

            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = colorMain
                ds.isUnderlineText = false
            }
        },userAgreementStart,userAgreementEnd,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
        //隐私政策
        spannableStringBuilder.setSpan(object :ClickableSpan(){
            override fun onClick(widget: View) {

            }

            override fun updateDrawState(ds: TextPaint) {
                ds.color = colorMain
                ds.isUnderlineText = false
            }
        },privacyPolicyStart,privacyPolicyEnd,Spannable.SPAN_EXCLUSIVE_INCLUSIVE)

        mBinding.tvAgreement.highlightColor = Color.TRANSPARENT
        mBinding.tvAgreement.movementMethod = LinkMovementMethod.getInstance()
        mBinding.tvAgreement.text = spannableStringBuilder
    }


}

